var express = require('express');
var router = express.Router();
var { ShopModel } = require("../model/model")
let jwt = require("jsonwebtoken")
const { Await } = require('react-router-dom');

// accessToken校验中间件
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  if (!token) {
    return res.status(401).json({ error: '未提供accessToken' });
  }
  jwt.verify(token, 'your_secret_key', (err, user) => {
    if (err) {
      return res.status(401).json({ error: 'accessToken无效或已过期' });
    }
    req.user = user;
    next();
  });
}

/* 获取数据*/
router.get('/list', authenticateToken, async (req, res) => {
  let { page, pageSize } = req.query
  page = parseInt(page)
  pageSize = parseInt(pageSize)
  let list = await ShopModel.find().skip((page - 1) * pageSize).limit(pageSize)
  const totalCount = await ShopModel.countDocuments()
  const totalPages = Math.ceil(totalCount / pageSize)
  res.send({
    code: 200,
    list,
    totalCount,
    totalPages,
    pageSize,
    currentPage:page
  })
})

/* 添加数据*/
router.post('/add', authenticateToken, async (req, res) => {
  await bbs.create(req.body)
  res.send({
    code: 200
  })
})

/* 修改数据*/
router.post('/edit', authenticateToken, async (req, res) => {
  await bbs.find(req.body).updateOne({ state: 0 })
  res.send({
    code: 200
  })
})

// 批量启售
router.post('/startmany', authenticateToken, async (req, res) => {
  const { ids } = req.body
  console.log(ids);
  await ShopModel.updateMany({ id: { $in: ids } }, { status: 1 })
  res.send({
    code: 200
  })
})

// 批量停售
router.post('/stopmany', authenticateToken, async (req, res) => {
  const { ids } = req.body
  console.log(ids);
  await ShopModel.updateMany({ id: { $in: ids } }, { status: 0 })
  res.send({
    code: 200
  })
})

/* 删除数据（单删）*/
router.post('/delone', authenticateToken, async (req, res) => {
  const { id } = req.body
  console.log(id);
  await ShopModel.deleteOne({ id })
  res.send({
    code: 200
  })
})

/* 批量删除数据*/
router.post('/delmany', authenticateToken, async (req, res) => {
  const { ids } = req.body

  console.log(ids);
  await ShopModel.deleteMany({ id: { $in: ids } })
  res.send({
    code: 200
  })
})

// 搜索
router.get('/search', async (req, res) => {
  const { name } = req.query

  let list1 = await ShopModel.find({
    name: new RegExp(name)
  })
  res.send({
    code: 200,
    list1
  })
})




module.exports = router;
